/*
 * AS3935.c
 *
 *  Created on: Sep 5, 2020
 *      Author: daniel
 */

#include "AS3935.h"

extern I2C_HandleTypeDef hi2c1;

#define AS3935_I2C		hi2c1
#define AS3935_ADDR		0x01

//static	uint8_t			as3935_irq = 0;

bool AS3935_Init()
{
	// 初始化
	// 室外模式
	uint8_t		data[2];

	data[0] = AFE_GAIN;
	data[1] = OUTDOOR << 1;

	if (HAL_I2C_Master_Transmit(&AS3935_I2C, AS3935_ADDR<<1, data, 2, 100) != HAL_OK) {
		return false;
	}


	data[0] = INT_MASK_ANT;
	data[1] = 0x20;
	if (HAL_I2C_Master_Transmit(&AS3935_I2C, AS3935_ADDR<<1, data, 2, 100) != HAL_OK) {
		return false;
	}

	// 读取一次IRQ寄存器，清除之前遗留的状态。
	if (HAL_I2C_Mem_Read(&AS3935_I2C, AS3935_ADDR<<1, INT_MASK_ANT, I2C_MEMADD_SIZE_8BIT, data, 1, 100) != HAL_OK) {
		return false;
	} else {
		return true;
	}
}

//void AS3935_ISR()
//{
//	as3935_irq = 1;
//}
//
//void AS3935_CheckISR()
//{
//	__disable_irq();
//
//	if (as3935_irq == 1) {
//		as3935_irq = 2;
//	}
//	__enable_irq();
//}

bool AS3935_GetData(enum INTERRUPT_STATUS* type, uint16_t* dist)
{
	HAL_StatusTypeDef 	status = 0;
	uint8_t				data;

	// 读取IRQ寄存器
	if (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_8) == GPIO_PIN_SET) {
		status = HAL_I2C_Mem_Read(&AS3935_I2C, AS3935_ADDR<<1, INT_MASK_ANT, I2C_MEMADD_SIZE_8BIT, &data, 1, 100);

		if (status == HAL_OK) {
			*type = data & INT_MASK;

			if (*type == LIGHTNING) {
				// 读取距离
				status = HAL_I2C_Mem_Read(&AS3935_I2C, AS3935_ADDR<<1, DISTANCE, I2C_MEMADD_SIZE_8BIT, &data, 1, 100);

				if (status == HAL_OK) {
					*dist = data & DISTANCE_MASK;

					return true;
				} else {
					*dist = 0;
					return false;
				}
			}
		}
	}

	*dist = 0;
	return true;
}

